package com.tpshion.cloud.oss.controller;

import com.tpshion.cloud.common.support.CoreException;
import com.tpshion.cloud.common.support.ErrorCode;
import com.tpshion.cloud.common.support.Result;
import com.tpshion.cloud.core.annotation.Permission;
import com.tpshion.cloud.core.autoconfig.support.FileInfo;
import com.tpshion.cloud.core.autoconfig.support.FileObject;
import com.tpshion.cloud.core.autoconfig.support.MinioTemplate;
import com.tpshion.cloud.core.autoconfig.support.UploadResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.stream.Collectors;

@RestController
public class FileController {

    private static final Logger log = LoggerFactory.getLogger(FileController.class);

    @Autowired
    private MinioTemplate minioTemplate;

    /**
     * 上传文件
     * @param file 文件
     * @return
     */
    @PostMapping("/upload")
    @Permission("file:upload")
    public Result<?> upload(@RequestParam("file") MultipartFile file){
        double size = (file.getSize() / (1024.0 * 1024.0));
        log.info("*** uploadFile originalFilename:{} size:{}MB",file.getOriginalFilename(), String.format("%.2f", size));
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            log.error("fileName:{} 获取文件流异常：{}",file.getOriginalFilename(),e.getMessage());
            throw new CoreException(ErrorCode.FILE_UPLOAD_ERROR);
        }
        UploadResponse response = minioTemplate.simpleUpload(file.getOriginalFilename(), inputStream, file.getContentType());
        return Result.ok(response);
    }

    /**
     * 删除文件
     * @param fileName 文件名称
     * @return
     */
    @DeleteMapping("/delete/{fileName}")
    @Permission("file:delete")
    public Result<?> delete(@PathVariable("fileName") String fileName){
        minioTemplate.delete(fileName);
        return Result.ok();
    }

    /**
     * 获取文件列表
     * @return
     */
    @GetMapping("/files")
    public Result<?> getFiles(){
        FileInfo fileInfo = minioTemplate.getFileInfo();
        return Result.ok(fileInfo);
    }

    /**
     * 搜索文件
     */
    @GetMapping(value = "/file")
    public Result<?> searchFile(@RequestParam("fileName") String fileName){
        List<FileObject> fileObjects = minioTemplate.getFileObjects();
        List<FileObject> collect = fileObjects.stream()
                .filter(item -> item.getObjectName().contains(fileName))
                .collect(Collectors.toList());
        return Result.ok(collect);
    }
}
